package net.vz.geoapi.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class GeoProxy {
    
    public static String sendGetRequest(String endpoint, String requestParameters)
    {
        String result = null;
        if (!endpoint.startsWith("http://")) {
            new Exception("GET request failed! Url should start with http://!");
        }   
        
        try {
            // Construct data
            StringBuffer data = new StringBuffer();
            // Send data
            String urlStr = endpoint;
            if (requestParameters != null && requestParameters.length () > 0) {
                urlStr += "?" + requestParameters;
            }
           
           URL url = new URL(urlStr);
           URLConnection conn = url.openConnection();
           
           // Get the response
           BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
           StringBuffer sb = new StringBuffer();
           String line;
           while ((line = rd.readLine()) != null) {
               sb.append(line);
           }
           rd.close();
           result = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    
    public static String getUrlEncodedParams(Map<String, String> _params) throws UnsupportedEncodingException {
        
        Set<String> keys = _params.keySet();
        Iterator<String> setIterator = keys.iterator();
        String query = "";
        
        while (setIterator.hasNext()) {
            String key = setIterator.next();
            String value = URLEncoder.encode(_params.get(key), "UTF-8");
            
            query += key + "=" + value + "&"; 
        }
        return query;
    }
}
